layui.define(['index', 'form', 'table', 'tooltipster', 'laypage', '$http', 'zmnUtils', 'layedit', 'laydate', 'zmnBind', 'select2'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    var laydate = layui.laydate;
    var tooltipster = layui.tooltipster;
    var $http = layui.$http;
    var zmnUtils = layui.zmnUtils;
    var zmnBind = layui.zmnBind;
    var zmnApp = layui.zmnApp;
    var select2 = layui.select2;


    zmnBind.selectPlat("plat", null, false, false, false, null, function (values) {
    });

    zmnBind.selectlArea("ruleAreaProvinceId", "ruleAreaCityId", "ruleAreaCountyId", [], false);
    zmnBind.selectlPlatRegionCompany("firstOrgId", "secondOrgId", "thirdOrgId", [], false);

    var cols = [
        [
            {field: 'spId', type: 'checkbox', fixed: 'left', align: 'center'},
            {field: 'spId', title: '服务商ID', align: 'center', unresize: true, sort: false},
            {field: 'name', title: '服务商名称', align: 'center', unresize: true, sort: false},
            {field: 'fullName', title: '公司名称', align: 'center', unresize: true, sort: false},
            {
                field: 'plat', title: '所属平台', align: 'center', unresize: true, sort: false, templet: function (d) {
                    var plat = d.plat;
                    var text;
                    if (plat == 20) {
                        text = '言而有信';
                    } else if (plat == 10) {
                        text = '啄木鸟';
                    } else if (plat == 30) {
                        text = '一步维修';
                    } else if (plat == 40) {
                        text = '川南环保';
                    } else {
                        text = '';
                    }
                    return text;
                }
            },
            {
                field: 'twoType', title: '类型', align: 'center', unresize: true, sort: false, templet: function (d) {
                    let twoType = d.twoType;
                    let twoTypeText;
                    if (twoType == 10) {
                        twoTypeText = '直营';
                    } else if (twoType == 20) {
                        twoTypeText = '非直营';
                    } else {
                        twoTypeText = '';
                    }
                    let thirdType = d.thirdType;
                    let thirdTypeText;
                    if (thirdType == 10) {
                        thirdTypeText = '服务商';
                    } else if (thirdType == 20) {
                        thirdTypeText = '承包商';
                    } else if (thirdType == 30) {
                        thirdTypeText = '合伙人';
                    } else {
                        thirdTypeText = '';
                    }
                    return twoTypeText + '-' + thirdTypeText;
                }
            },
            {
                field: 'statementCycle',
                title: '结算周期',
                align: 'center',
                unresize: true,
                sort: false,
                templet: function (d) {
                    let countCycle = d.statementCycle;
                    let text;
                    if (countCycle == 1) {
                        text = '三天结';
                    } else if (countCycle == 2) {
                        text = '周结';
                    } else if (countCycle == 3) {
                        text = '十天结';
                    } else if (countCycle == 4) {
                        text = '十五天结';
                    } else if (countCycle == 5) {
                        text = '月结';
                    } else {
                        text = '';
                    }
                    return text;
                }
            },
            {
                field: 'bizType',
                title: '业务类型',
                align: 'center',
                unresize: true,
                sort: false,
                templet: function (d) {
                    let bizType = d.bizType;
                    let text = '';
                    if (bizType) {
                        let bizTypeArr = bizType.split(',');
                        let isFirst = true;
                        for (let i = 0; i < bizTypeArr.length; i++) {
                            let busType = bizTypeArr[i];
                            let busStr;
                            if (busType == '1') {
                                busStr = 'C';
                            } else if (busType == '2') {
                                busStr = 'F';
                            } else if (busType == '3') {
                                busStr = 'B';
                            } else {
                                busStr = busType;
                            }
                            if (isFirst) {
                                text += busStr;
                                isFirst = false;
                            } else {
                                text += ',' + busStr;
                            }
                        }
                    }
                    return text;
                }
            },
            {
                field: 'status', title: '状态', align: 'center', unresize: true, sort: false, templet: function (d) {
                    var status = d.status;
                    var text;
                    if (status == 1) {
                        text = '停用';
                    } else if (status == 2) {
                        text = '启用';
                    } else {
                        text = '';
                    }
                    return text;
                }
            },
            {
                field: 'createTime',
                title: '创建时间',
                align: 'center',
                width: '10%',
                unresize: true,
                templet: function (d) {
                    return zmnUtil.createTime(d.createTime);
                }
            },
            {
                fixed: 'right', title: '选择', align: 'center', templet: function (d) {
                    return '<a class="layui-btn layui-btn-xs btn-operate" id="selectSpItem"' +
                        ' onclick="addItem(' + d.spId + ')" >选择</a>';
                }
            }
        ]
    ];

    $.ajaxSetup({
        crossDomain: true,
        xhrFields: {withCredentials: true}
    });

    let query;
    form.on('submit(zmn-form-submit)', function (obj) {
        query = obj.field;
        tableRender(query);
        return false;
    });

    let tableRender = function (data) {
        layTableRender(table, cols, "zmn-table", data, "/channel/sp/listPageByQuery", {
            height: 'full-150', defaultToolbar: [], done: function (res) {

            }
        });
    };

    // 查询服务商
    tableRender();

    // 选择框清空
    $('.select-clear-icon').hover(function () {
        $(this).css('position', 'relative');
        $(this).append('<i title="清空" del style="position:absolute;top:3px;right:30px;cursor: pointer;font-size: 14px;">×</i>');
        $(this).find('i[del]').bind('click', function () {
            $(this).parent().find('select').val('');
            form.render('select');
        });
    }, function () {
        $(this).css('position', 'static');
        $(this).find('i[del]').remove();
    });


    var spId;
    $(document).on('mouseover', '.btn-operate', function () {
        spId = $(this).attr('data-th-data-id');
    });

    //查询条件重置
    form.on('submit(zmn-firm-sp-form-reset)', function (obj) {
        form.val("zmn-firm-sp-filter", {
            "firstOrgId": ""
            , "secondOrgId": ""
            , "thirdOrgId": ""
            , "spId": ""
            , "plat": ""
        });
        $('.select2-selection__rendered').html('<span class="select2-selection__placeholder">全部</span>');
        tableRender();
        return false;
    });

    /**
     * 初始化实时搜索下拉框
     */
    function initSelecteBySelect2() {
        $('#spId').select2({
            theme: "layui",
            language: 'zh-CN',
            placeholder: '全部',
            allowClear: true,
            minimumInputLength: 1,
            dropdownAutoWidth: true,
            ajax: {
                url: '/channel/sp/findSpProviderByKeyword',
                dataType: 'json',
                crossDomain: true,
                xhrFields: {withCredentials: true},
                delay: 250,
                data: function (params) {
                    var eleId = $(this).attr('id');
                    var searchType = 1;
                    if (eleId == 'mobile') {
                        searchType = 2;
                    }
                    query = {
                        searchType: searchType,
                        key: params.term
                    };
                    return query;
                },
                processResults: function (response) {
                    var results = [];
                    if (response.status === 200) {
                        results = response.data;
                    }
                    results = results.map((item) => {
                        item.id = item.key;
                        item.text = item.value;
                        return item;
                    });
                    return {
                        results: results
                    };
                }
            },
            escapeMarkup: function (markup) {
                return markup;
            },
            templateResult: formatRepoForMaster
        });
    }

    /**
     * 格式化数据
     */
    function formatRepoForMaster(repo) {
        if (repo.loading) {
            return '查询中...'
        }
        var name = repo.text;
        return '<div><div><span>' + name + '</span></div></div>';
    }

    initSelecteBySelect2();

    function layTableRender(table, cols, id, data, url, parameter) {
        if (parameter !== undefined) {
            let {
                height,
                elem,
                toolbar,
                defaultToolbar,
                title,
                loading,
                done,
                page,
                skin,
                even,
                size,
                layout
            } = parameter;
        }
        let defaultParameter = {
            elem: "#" + id
            , toolbar: "#" + id + "-tool"
            , defaultToolbar: ['filter'] // ['filter', 'print', 'exports']
            , loading: true
            , page: {
                prev: "上一页"
                , next: "下一页"
                , hash: true
                , limit: 50
                , limits: [50, 100, 150]
                , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
            },

        };

        let normalParameter = Object.assign({}, defaultParameter, parameter);

        table.render({
            id: id
            , url: url
            , where: data
            , cols: cols
            , elem: normalParameter.elem
            , layout: normalParameter.layout
            , defaultToolbar: normalParameter.defaultToolbar
            , toolbar: normalParameter.toolbar
            , title: normalParameter.title
            , limit: (normalParameter.page === true) ? normalParameter.limit : undefined
            , limits: (normalParameter.page === true) ? normalParameter.limits : undefined
            , height: normalParameter.height
            , loading: normalParameter.loading
            , done: normalParameter.done
            , page: normalParameter.page
            , skin: normalParameter.skin
            , even: normalParameter.even
            , size: normalParameter.size
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit       //?curr=1&nums=30
            }
            , response: {
                statusName: 'status' //规定数据状态的字段名称，默认：code
                , statusCode: 200 //规定成功的状态码，默认：0
                , msgName: 'message' //规定状态信息的字段名称，默认：msg
                , countName: 'count' //规定数据总数的字段名称，默认：count
                , dataName: 'data' //规定数据列表的字段名称，默认：data
            },
            parseData: function (result) {
                result.count = result.data.count;
                result.data = result.data.data;
                return result;
            }
        });
    }

    form.on("select(twoType)", function (obj) {
        let val = obj.value;
        let thirdTypeDom = $("#thirdType");
        thirdTypeDom.empty();
        thirdTypeDom.append('<option value="">全部</option>');
        if (val) {
            if (val == 10) {
                thirdTypeDom.append('<option value="10">直营</option><option value="30">合伙人</option>');
            }
            if (val == 20) {
                thirdTypeDom.append('<option value="20">承包商</option>');
            }
        }
        form.render("select");
    });


    //【表格左上侧工具栏监听】
    table.on("toolbar(zmn-table)", function (obj) {

        if (obj.event == "select") {
            var data = table.checkStatus('zmn-table').data;
            var spIds = [];
            for (var i = 0; i < data.length; i++) {
                spIds.push(data[i].spId);
            }
            if (spIds.length === 0) {
                return layer.alert("请选择至少一条数据！");
            }

            layer.confirm('确认添加服务商吗？', function () {
                ajaxSimple("/channel/sp/add", {
                    'spIds': spIds.join(","),
                    'channelId': json.channelId,
                    'type': json.type
                });

                // setTimeout('parent.layui.table.reload("zmn-table")', 2000);
                setTimeout('parent.location.reload()', 1500);
            });
            parent.layui.table.init()
            return false;
        }
    });

    //对外暴露的接口
    exports('sp_list', {});
});

//  表格选择按钮(单选)
function addItem(spId) {
    console.log(spId)
    if (zmnUtil.isEmptyNull(spId)) {
        return layer.alert("请选择至少一条数据！");
    }
    layer.confirm('确认添加服务商吗？', function () {
        ajaxSimple("/channel/sp/add", {
            'spIds': spId,
            'channelId': json.channelId,
            'type': json.type
        });
        // setTimeout('parent.layui.table.reload("zmn-table")', 2000);
        setTimeout('parent.location.reload()', 1500);
    });

    return false;
}

function ajaxSimple(url, data) {
    var $ = layui.$;
    $.ajax({
        type: "POST", url: url,
        dataType: "json", data: data,
        success: function (json) {
            layer.msg(json.message);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}